using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows.Input;
using WebServiceTool.Models;
using WebServiceTool.Services;
using WebServiceTool.Utilities;

namespace WebServiceTool.ViewModels
{
    /// <summary>
    /// WebService测试的ViewModel类，负责处理WebService调用相关的UI逻辑和数据绑定
    /// </summary>
    public sealed class MainWindowViewModel : INotifyPropertyChanged
    {

        #region 字段

        /// <summary>
        ///   WebService服务
        /// </summary>
        private readonly IWebService _webService;

        private string _statusText = "就绪";

        // WebService测试相关字段
        private string _wsdlUrl = "http://www.dneonline.com/calculator.asmx?wsdl";

        // 方法列表
        private ObservableCollection<WebServiceOperation> _serviceMethods = new ObservableCollection<WebServiceOperation>();

        // 过滤后的方法列表
        private ObservableCollection<WebServiceOperation> _filteredMethods;

        // 当前选中的方法
        private WebServiceOperation _selectedOperation;

        // 是否正在发送请求 默认值为false
        private bool _isHttpRequesting;

        // wsdl 内容
        private string _content;

        // 打开的方法列表
        private ObservableCollection<MethodDetailViewModel> _openMethods;

        // 当前打开的方法
        private MethodDetailViewModel _selectedOpenMethod;

        // 方法过滤关键字
        private string _filterWords = "";

        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="webService">WebService服务</param>
        public MainWindowViewModel(IWebService webService)
        {
            _webService = webService;

            // 初始化命令
            GetWsdlMethodsCommand = new RelayCommand(GetWsdlMethodsWrapper,
                () => !IsHttpRequesting);
            // 初始化打开的方法列表
            _openMethods = new ObservableCollection<MethodDetailViewModel>();

            // 初始化过滤后的方法列表
            _filteredMethods = new ObservableCollection<WebServiceOperation>();
        }

        #endregion

        #region 属性

        /// <summary>
        /// WSDL URL
        /// </summary>
        public string WsdlUrl
        {
            get => _wsdlUrl;
            set
            {
                _wsdlUrl = value;
                OnPropertyChanged();
            }
        }


        /// <summary>
        /// 服务方法列表
        /// </summary>
        public ObservableCollection<WebServiceOperation> ServiceMethods
        {
            get => _serviceMethods;
            set
            {
                _serviceMethods = value;
                OnPropertyChanged();
                // 当原始方法列表改变时，重新应用过滤
                ApplyFilter();
            }
        }

        /// <summary>
        /// 过滤后的方法列表（用于UI显示）
        /// </summary>
        public ObservableCollection<WebServiceOperation> FilteredMethods
        {
            get => _filteredMethods;
            set
            {
                _filteredMethods = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 选中的方法
        /// </summary>
        public WebServiceOperation SelectedOperation
        {
            get => _selectedOperation;
            set
            {
                _selectedOperation = value;
                OnPropertyChanged();

                // 当选中方法改变时，打开新选项卡
                if (_selectedOperation != null)
                {
                    OpenMethodInNewTab(_selectedOperation);
                }
            }
        }

        /// <summary>
        /// 打开的方法列表（用于选项卡显示）
        /// </summary>
        public ObservableCollection<MethodDetailViewModel> OpenMethods
        {
            get => _openMethods;
            set
            {
                _openMethods = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 选中的打开方法（用于选项卡选择）
        /// </summary>
        public MethodDetailViewModel SelectedOpenMethod
        {
            get => _selectedOpenMethod;
            set
            {
                _selectedOpenMethod = value;
                OnPropertyChanged();
            }
        }

        /// <summary>
        /// 是否正在发送请求
        /// </summary>
        public bool IsHttpRequesting
        {
            get => _isHttpRequesting;
            set
            {
                _isHttpRequesting = value;
                OnPropertyChanged();
                // 通知命令重新评估是否可以执行
                if (GetWsdlMethodsCommand is RelayCommand getWsdlRelayCommand)
                {
                    getWsdlRelayCommand.RaiseCanExecuteChanged();
                }
            }
        }

        #endregion

        #region 命令

        /// <summary>
        /// 获取WSDL方法命令
        /// </summary>
        public ICommand GetWsdlMethodsCommand { get; }


        /// <summary>
        /// 状态文本
        /// </summary>
        public string StatusText
        {
            get => _statusText;
            set
            {
                if (_statusText == value) return;

                _statusText = value;
                OnPropertyChanged();
            }
        }

        public string FilterWords
        {
            get => _filterWords;
            set
            {
                if (_filterWords == value) return;

                _filterWords = value;
                OnPropertyChanged();
                // 当过滤词改变时，重新应用过滤
                ApplyFilter();
            }
        }

        #endregion

        #region 私有方法 - 命令包装器

        /// <summary>
        /// 获取WSDL方法命令的包装方法
        /// </summary>
        private async void GetWsdlMethodsWrapper()
        {
            try
            {
                await GetWsdlMethods();
            }
            catch (Exception ex)
            {
                StatusText = $"获取WSDL方法时发生错误:{ex.Message}";
            }
        }

        #endregion

        #region 私有方法 - 选项卡管理

        /// <summary>
        /// 在新选项卡中打开方法
        /// </summary>
        /// <param name="operation">要打开的方法</param>
        private void OpenMethodInNewTab(WebServiceOperation operation)
        {
            // 检查方法是否已经打开
            var existingTab = _openMethods.FirstOrDefault(m => m.Operation.Name == operation.Name);
            if (existingTab != null)
            {
                // 如果已经打开，则选中该选项卡
                SelectedOpenMethod = existingTab;
                return;
            }

            // 创建新选项卡
            var methodViewModel = new MethodDetailViewModel(operation, _webService, _content);
            _openMethods.Add(methodViewModel);
            SelectedOpenMethod = methodViewModel;
        }

        #endregion

        #region 私有方法 - WebService操作

        /// <summary>
        /// 获取WSDL内的方法
        /// </summary>
        private async Task GetWsdlMethods()
        {
            IsHttpRequesting = true;
            StatusText = "正在获取WSDL...";

            try
            {
                _content = await _webService.GetWsdlAsync(WsdlUrl);


                // 解析WSDL并获取服务方法
                StatusText = "正在解析WSDL...";
                var methods = await _webService.ParseWsdlMethods(_content);
                ServiceMethods = new ObservableCollection<WebServiceOperation>(methods);
                StatusText = $"解析完成，找到 {methods.Count} 个方法";

                // 清空已打开的选项卡
                OpenMethods.Clear();
                SelectedOpenMethod = null;
            }
            catch (Exception ex)
            {
                ServiceMethods = new ObservableCollection<WebServiceOperation>();
                StatusText = $"WSDL获取失败{ex.Message}";
                throw;
            }
            finally
            {
                IsHttpRequesting = false;
            }
        }

        #endregion


        #region 私有方法 - 过滤功能

        /// <summary>
        /// 应用过滤条件到方法列表
        /// </summary>
        private void ApplyFilter()
        {
            // 如果没有过滤词，则显示所有方法
            if (string.IsNullOrWhiteSpace(FilterWords))
            {
                FilteredMethods = new ObservableCollection<WebServiceOperation>(ServiceMethods);
                return;
            }

            // 根据过滤词筛选方法（不区分大小写）
            var filtered = ServiceMethods.Where(method =>
                method.Name.ToLower().Contains(FilterWords.ToLower())
            ).ToList();

            FilteredMethods = new ObservableCollection<WebServiceOperation>(filtered);
        }

        #endregion

        #region INotifyPropertyChanged实现

        // 事件
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// 触发属性更改事件
        /// </summary>
        /// <param name="propertyName">属性名</param>
        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion

    }
}